// 语言控制包
package languageswitcher

import (
	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type LanguageSwitcher struct {
	session *mgo.Session
	dbName  string
}

const (
	CollectionLanguages string = "languages" //多语言表
)

// 构造函数
func NewLanguageSwitcher(session *mgo.Session, dbName string) *LanguageSwitcher {
	ls := LanguageSwitcher{session: session, dbName: dbName}
	return &ls
}

// 根据文本Id获取指定语言的内容字符串
func (p *LanguageSwitcher) Get(textId int, lang string) string {
	if lang == "" {
		//默认为英文
		lang = "cn"
	}

	s := p.session.Copy()
	defer s.Close()

	c := s.DB(p.dbName).C(CollectionLanguages)
	var res map[string]string

	err := c.Find(bson.M{"id": textId}).Select(bson.M{"_id": 0, "en": 1, lang: 1}).One(&res)
	if err != nil {
		return ""
	} else {
		if lang == "en" {
			return res["en"]
		} else {
			text := res[lang]
			if text == "" {
				text = res["en"]
			}
			return text
		}
	}
}
